package com.tg.service.utils;

import org.springframework.context.ApplicationContext;

/**
 * Created by linzc on 2018/9/20.
 */
public class ContextUtil {
    /**
     * 全局容器
     */
    protected static ApplicationContext applicationContext;

    /**
     * 构造函数
     */
    private ContextUtil() {
        /*什么都没有*/
    }

    /**
     * 读取BEAN
     *
     * @param classz 类
     * @param <T>    泛型
     * @return 对应的bean
     */
    public static <T> T getBean(Class<T> classz) {
        if (applicationContext == null) {
            return null;
        }
        return applicationContext.getBean(classz);
    }

    /**
     * 读取BEAN
     *
     * @param classz 类
     * @param <T>    泛型
     * @return 对应的bean
     */
    public static <T> T getBean(String name) {
        if (applicationContext == null) {
            return null;
        }
        Object obj = applicationContext.getBean(name);
        return (T) obj;
    }

    /**
     * ApplicationContext注入
     *
     * @param context ApplicationContext
     */
    public static void setApplicationContext(ApplicationContext context) {
        applicationContext = context;
    }

    /**
     * ApplicationContext注入
     *
     * @param context ApplicationContext
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
}

